package com.cloudkinto.service.invoice.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.common.NumberFormater;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.CompanyDo;
import com.cloudkinto.entity.DicBusinessItemDo;
import com.cloudkinto.entity.InvoiceRecordDo;
import com.cloudkinto.entity.InvoiceTitleDo;
import com.cloudkinto.extentity.InvoiceRecordDto;
import com.cloudkinto.service.invoice.InvoiceRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.invoice.InvoiceTitleService;
import com.cloudkinto.service.invoice.vo.InvoiceRecordAddReq;
import com.cloudkinto.service.invoice.vo.InvoiceRecordDetailRes;
import com.cloudkinto.service.invoice.vo.InvoiceRecordUpdateReq;
import io.swagger.annotations.ApiResponse;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 *  service实现类
 * </p>
 * @author hjy
 * @since 2021-07-13
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class InvoiceRecordServiceImpl extends ServiceImpl<InvoiceRecordDao, InvoiceRecordDo> implements InvoiceRecordService {
    @Autowired
    private InvoiceRecordDao dao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private InvoiceTitleService invoiceTitleService;
    @Autowired
    private InvoiceTitleDao invoiceTitleDao;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;

    @Override
    public SingleResult addInit(Long companyId) {
        Map map = new HashMap();
        //计算出可以开票得金额
        double allAmount = dao.getSumCostRecord(companyId);
        double hadInvoiceAmount = dao.getSumHadInvoiceAmount(companyId);
        map.put("leftAmount", new BigDecimal(allAmount-hadInvoiceAmount).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());

        //查询可以选择得发票抬头
        List<Map> invoiceList = invoiceTitleService.selectInvoiceListInit(companyId);
        map.put("invoiceTitleList",invoiceList);

        //查询上次开票使用的开票抬头
        CompanyDo companyDo = companyDao.selectById(companyId);
        if (companyDo != null && companyDo.getLastInvoiceTitleId() != null && companyDo.getLastInvoiceTitleId() != 0){
            InvoiceTitleDo lastInvoiceTitle = invoiceTitleDao.selectById(companyDo.getLastInvoiceTitleId());
            map.put("lastInvoiceTitle",lastInvoiceTitle);
            map.put("lastInvoiceType",companyDo.getLastInvoiceType());
        }
        return SingleResult.success(map);
    }

    @Override
    public InvoiceRecordAddReq add(InvoiceRecordAddReq req, Long userId) {
        if (req.getInvoiceTitleId() == null || req.getInvoiceTitleId() == 0){
            throw new BizException("请选择开票抬头!");
        }
        InvoiceTitleDo et = invoiceTitleDao.selectById(req.getInvoiceTitleId());
        if (et == null){
            throw new BizException("该开票抬头已过期，请重新选择!");
        }
        InvoiceRecordDo entityDo = new InvoiceRecordDo();
        BeanUtils.copyProperties(req, entityDo);
        entityDo.setBank(et.getBank());
        entityDo.setBankAccount(et.getBankAccount());
        entityDo.setCompanyAddress(et.getCompanyAddress());
        entityDo.setCompanyTelephone(et.getCompanyTelephone());
        entityDo.setInvoiceTitle(et.getInvoiceTitle());
        entityDo.setTaxNumber(et.getTaxNumber());
        handlerAddBefore(entityDo, userId);
        if (entityDo.getStatus() == null || entityDo.getStatus() == 0L){
            entityDo.setStatus(DicBusinessItemConstant.invoiceApplyStatus);
        }
        //固定月开先不生成记录，由定时器每月9号自动生成
        if (entityDo.getType() == 1) {
            if (entityDo.getInvoiceAmount() == null || entityDo.getInvoiceAmount() <= 0){
                throw new BizException("请输入有效的开票金额");
            }
            //一次开票，判断每月是否由开票记录
            QueryWrapper<InvoiceRecordDo> queryWrapper = new QueryWrapper<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            String strDate = sdf.format(new Date());
            queryWrapper.eq("company_id",entityDo.getCompanyId()).last(String.format(" and DATE_FORMAT(create_time,'%1$s') = '%2$s' limit 1","%Y-%m",strDate));
            InvoiceRecordDo record = dao.selectOne(queryWrapper);
            if (record != null){
                throw new BizException("每月只可以开票一次!");
            }
            if (!updateCheck(req.getCompanyId(),req.getInvoiceAmount())){
                throw new BizException("剩余开票余额不足!");
            }
            dao.insert(entityDo);
        }
        //开票成功后，将开票抬头id 保存到t_company表中
        updateCompanyMsg(req.getInvoiceTitleId(),req.getType(),req.getCompanyId());
        return req;
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(InvoiceRecordDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(InvoiceRecordDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id,Long companyId) {
        InvoiceRecordDo et = dao.selectById(id);
        if (et == null){
            throw new BizException("该数据已被删除!");
        }
        Map map = new HashMap();
        //计算出可以开票得金额
        double allAmount = dao.getSumCostRecord(companyId);
        double hadInvoiceAmount = dao.getSumHadInvoiceAmount(companyId);
        map.put("leftAmount",new BigDecimal(allAmount-hadInvoiceAmount+et.getInvoiceAmount()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());

        //查询可以选择得发票抬头
        List<Map> invoiceList = invoiceTitleService.selectInvoiceListInit(companyId);
        map.put("invoiceTitleList",invoiceList);
        InvoiceRecordUpdateReq req = new InvoiceRecordUpdateReq();

        //判断下开票得状态
        if (!et.getStatus().equals(DicBusinessItemConstant.invoiceApplyStatus)){
            String msg = DicBusinessItemConstant.invoicePassStatus.equals(et.getStatus()) ? "审核通过" : (DicBusinessItemConstant.invoiceNotPassStatus.equals(et.getStatus())
                    ? "作废" : (DicBusinessItemConstant.invoiceSuccessStatus.equals(et.getStatus()) ? "开票成功" : "审核通过"));
            throw new BizException("该发票已经"+msg+"，无法修改!");
        }
        BeanUtils.copyProperties(et,req);
        map.put("InvoiceRecord",req);
        return SingleResult.success(map);
    }

    @Override
    public InvoiceRecordUpdateReq update(InvoiceRecordUpdateReq req, Long userId) {
        InvoiceRecordDo entityDo = dao.selectById(req.getId());
        if (entityDo == null){
            throw new BizException("该数据已被删除!");
        }
        //判断下开票得状态
        if (!entityDo.getStatus().equals(DicBusinessItemConstant.invoiceApplyStatus)){
            String msg = DicBusinessItemConstant.invoicePassStatus.equals(entityDo.getStatus()) ? "审核通过" : (DicBusinessItemConstant.invoiceNotPassStatus.equals(entityDo.getStatus())
            ? "作废" : (DicBusinessItemConstant.invoiceSuccessStatus.equals(entityDo.getStatus()) ? "开票成功" : "审核通过"));
            throw new BizException("该发票已经"+msg+"，无法修改!");
        }
        //更新时需要将本条开票记录 的开票金额另算
        if (!updateCheck(req.getCompanyId(),req.getInvoiceAmount()-entityDo.getInvoiceAmount())){
            throw new BizException("剩余开票余额不足!");
        }
        if (req.getInvoiceTitleId() != null && req.getInvoiceTitleId() != 0L){
            InvoiceTitleDo et = invoiceTitleDao.selectById(req.getInvoiceTitleId());
            if (et == null){
                throw new BizException("该开票抬头已过期，请重新选择!");
            }

            //更新t_company表中的上次开票抬头id
            updateCompanyMsg(req.getInvoiceTitleId(),req.getType(),req.getCompanyId());
            //由titileId说明修改了该条开票信息的公司抬头，更新抬头信息
            entityDo.setBank(et.getBank());
            entityDo.setBankAccount(et.getBankAccount());
            entityDo.setCompanyAddress(et.getCompanyAddress());
            entityDo.setCompanyTelephone(et.getCompanyTelephone());
            entityDo.setInvoiceTitle(et.getInvoiceTitle());
            entityDo.setTaxNumber(et.getTaxNumber());
        }
        entityDo.setType(req.getType());
        entityDo.setInvoiceAmount(req.getInvoiceAmount());
//        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);

        return req;
    }

    public void updateCompanyMsg(Long invoiceTitleId,Integer type,Long companyId){
        //开票成功后，将开票抬头id 保存到t_company表中
        CompanyDo companyDo = new CompanyDo();
        companyDo.setId(companyId);
        companyDo.setLastInvoiceTitleId(invoiceTitleId);
        companyDo.setLastInvoiceType(type);
        companyDao.updateById(companyDo);
    }
    //编辑校验
    private boolean updateCheck(Long companyId,double invoiceAmount) {
        double allAmount = dao.getSumCostRecord(companyId);
        double hadInvoiceAmount = dao.getSumHadInvoiceAmount(companyId);
        if ((allAmount - hadInvoiceAmount) < invoiceAmount){
            return false;
        }
        return true;
    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(InvoiceRecordDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(InvoiceRecordDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        InvoiceRecordDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(InvoiceRecordDo entityDo, Long userId) {
//        entityDo.setDeleteBy(userId);
//        entityDo.setDeleteTime(new Date());
    }

    @Override
    public InvoiceRecordDetailRes detail(Long id) {
        InvoiceRecordDo entityDo =  dao.selectById(id);
        InvoiceRecordDetailRes req = new InvoiceRecordDetailRes();
        if (entityDo != null) {
            BeanUtils.copyProperties(entityDo, req);
        }
        handlerDetailAfter(req);
        return req;
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(InvoiceRecordDetailRes res) {
        CompanyDo companyDo = companyDao.selectById(res.getCompanyId());
        if (companyDo != null){
            res.setCompanyName(companyDo.getName());
        }
        res.setApplyTime(res.getCreateTime());
        return res;
    }

    @Override
    public SingleResult pageInit() {
        Map result = new HashMap();
        //查询开票状态
        List<Map> invoiceStatusList = new ArrayList<>();
        LambdaQueryWrapper<DicBusinessItemDo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DicBusinessItemDo :: getDicBusinessId, DicBusinessConstant.invoiceStatus);
        List<DicBusinessItemDo> invoiceStatusItems = dicBusinessItemDao.selectList(lambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(invoiceStatusItems)){
            invoiceStatusItems.forEach(et -> {
                Map map = new HashMap();
                map.put("id",et.getId());
                map.put("name",et.getDicItemValue());
                invoiceStatusList.add(map);
            });
        }
        result.put("invoiceStatusList",invoiceStatusList);

        Map map1 = new HashMap();
        map1.put("id",0);
        map1.put("name","固定月开");
        Map map2 = new HashMap();
        map2.put("id",1);
        map2.put("name","一次开票");
        List<Map> invoiceTypeList = Arrays.asList(map1,map2);
        result.put("invoiceTypeList",invoiceTypeList);

        return SingleResult.success(result);
    }

    @Override
    public List<InvoiceRecordDetailRes> getList(Map<String, String> map) {
        QueryWrapper<InvoiceRecordDo> wrapper = queryBuild(map);
        List<InvoiceRecordDo> list = this.list(wrapper);
        List<InvoiceRecordDetailRes> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
//        QueryWrapper<InvoiceRecordDo> wrapper = queryBuild(map);
        IPage<InvoiceRecordDto> page = pageInitDto(map);
//        page = this.page(page, wrapper);
        List<InvoiceRecordDto> recordDos = dao.listPageDto(page,map);
        List<InvoiceRecordDetailRes> resList = handlerListAfterDto(recordDos);
        PageResult result = new PageResult(resList, (int)page.getCurrent(), (int)page.getSize(), (int)page.getTotal(), (int)page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<InvoiceRecordDetailRes> handlerListAfterDto(List<InvoiceRecordDto> list ){
        List<InvoiceRecordDetailRes> result = new ArrayList<>();
        for (InvoiceRecordDto et : list) {
            InvoiceRecordDetailRes req = new InvoiceRecordDetailRes();
            BeanUtils.copyProperties(et,req);
            result.add(req);
        }
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<InvoiceRecordDetailRes> handlerListAfter(List<InvoiceRecordDo> list ){
        List<InvoiceRecordDetailRes> result = new ArrayList<>();
        for (InvoiceRecordDo et : list) {
            InvoiceRecordDetailRes req = new InvoiceRecordDetailRes();
            BeanUtils.copyProperties(et,req);
            CompanyDo companyDo = companyDao.selectById(req.getCompanyId());
            if (companyDo != null){
                req.setCompanyName(companyDo.getName());
            }
            result.add(req);
        }
        return result;
    }

    private IPage<InvoiceRecordDo> pageInit(Map<String, String> map) {
        IPage<InvoiceRecordDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }
    private IPage<InvoiceRecordDto> pageInitDto(Map<String, String> map) {
        IPage<InvoiceRecordDto> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<InvoiceRecordDo> queryBuild(Map<String, String> map) {
        QueryWrapper<InvoiceRecordDo> wrapper = new QueryWrapper<>();
//        if (StringUtils.isNotBlank(map.get("keyword"))) {
//            wrapper.and(invoiceRecordDoQueryWrapper -> invoiceRecordDoQueryWrapper.like("invoice_title",map.get("keyword"))
//                    .or().like("bank", map.get("keyword")));
//        }
        if (StringUtils.isNotBlank(map.get("status"))){
            wrapper.and(invoiceRecordDoQueryWrapper -> invoiceRecordDoQueryWrapper.eq("status",map.get("status")));
        }
        if (StringUtils.isNotBlank(map.get("type"))){
            wrapper.and(invoiceRecordDoQueryWrapper -> invoiceRecordDoQueryWrapper.eq("`type`",map.get("type")));
        }
        return wrapper;
    }

    @Override
    public Map<String,Object> getInvoiceTitle(Long id){
        InvoiceTitleDo invoiceTitleDo = invoiceTitleDao.selectById(id);
        Map<String,Object> msg = new HashMap<>();
        if (invoiceTitleDo != null){
            msg.put("id",invoiceTitleDo.getId());
            msg.put("invoiceTitle",invoiceTitleDo.getInvoiceTitle());
            msg.put("taxNumber",invoiceTitleDo.getTaxNumber());
            msg.put("companyAddress",invoiceTitleDo.getCompanyAddress());
        }
        return msg;
    }

}
